package com.xiaolei.library.Base;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;

/**
 * 可以使用LiveData的生命周期的后台服务
 */
public abstract class BaseService extends Service implements LifecycleOwner
{
    private LifecycleRegistry registry = new LifecycleRegistry(this);

    @Override
    public void onCreate()
    {
        super.onCreate();
        registry.setCurrentState(Lifecycle.State.CREATED);
        registry.setCurrentState(Lifecycle.State.STARTED);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if (registry.getCurrentState() != Lifecycle.State.RESUMED)
            registry.setCurrentState(Lifecycle.State.RESUMED);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy()
    {
        registry.setCurrentState(Lifecycle.State.DESTROYED);
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle()
    {
        return registry;
    }
}
